var util = require('../../../utils/util.js');
var dbUtil = require('../../../utils/db.js');
//获取应用实例
const app = getApp();
const db = wx.cloud.database();
Page({
  data: {
    topicList:[],
    hidden: false,
    //删除评论标识
    delIndex:null,
    delId:null
  },

  onLoad: function (options) {
    this.fetchData();
  },

  onPullDownRefresh: function()
  {
    this.setData({ hidden: false });
    this.fetchData();
  },

  // 获取数据
  fetchData: function () {
    var that = this;
  
    var openid = app.globalData.openid;
    db.collection('bbs_topic').where({
      _openid: openid
    }).get().then(res => {
      var topicList =  res.data.map(function (item) {
        item.create_at = util.getDateDiff(new Date(item.create_at));
        item.isOpen=false;
        return item;
      })
      that.setData({ topicList: topicList });
    });

    setTimeout(function () {
      that.setData({ hidden: true });
    }, 300);
  },

  // 点击删除按钮
  handleDelete: function (e) {
    var index = e.currentTarget.dataset.idx;
    var id = e.currentTarget.dataset.id;
    //验证有无评论
    db.collection('common_comment').where({
      topic_id: id
    }).count().then(res => {
      const count = res.total;
      if (count>0)
      {
        util.showErrorToast("已被评论");
      }else{
        db.collection('bbs_topic').doc(id).remove().then(res => {
          //被删除的贴子
          var delTopic = this.data.topicList[index];
          this.data.topicList.splice(index, 1);
          this.setData({ topicList: this.data.topicList });
          wx.showToast({ title: "删除成功" });

          //贴子删除了，它下面的图片，也连带删除
          var imgs = delTopic.imgs;
          if (null != imgs && imgs.length > 0) {
            wx.cloud.deleteFile({
              fileList: imgs,
              success: res => {
              },
              fail: res => {
              }
            })
          }

        });
      }
    })
  },
  // 左滑显示删除按钮
  handleSliderLeftStart: function (e) {
    this.data.topicList.forEach(todoItem => {
      // 除了当前项，其它打开项的菜单都关闭，确保每次只有一个项可以左滑显示删除
      if (todoItem.id !== e.target.dataset.id && todoItem.isOpen) {
        todoItem.isOpen = false
      }
    });
    this.setData({
      topicList: this.data.topicList
    })
  }
})
